#include "sdlMusic.h"

using std::string;

unsigned sdlMusic::counter = 0;
sdlMusicMonitor* sdlMusic::monitor = NULL;

void sdlMusic::init(){
	if (monitor == NULL){
		monitor = sdlMusicMonitor::getInstance();
	}
	counter++;
}

sdlMusic::sdlMusic(){
	this->init();
	this->music = NULL;
}

sdlMusic::sdlMusic(string path){
	this->init();
	this->load(path);
}

bool sdlMusic::load(string path){
	if (this->music != NULL){
		if (this->isPlaying()){this->stop();}
		Mix_FreeMusic(this->music);
		this->music = NULL;
	}
	this->music = Mix_LoadMUS(path.c_str());
	return this->music != NULL;
}

bool sdlMusic::isPlaying(){
	return Mix_PlayingMusic();
}

bool sdlMusic::play(){
	if (Mix_PlayMusic(this->music,-1) == -1){return false;}
	return true;
}

bool sdlMusic::isPaused(){
	return Mix_PausedMusic();
}

void sdlMusic::pause(){
	Mix_PauseMusic();
}

void sdlMusic::resume(){
	Mix_ResumeMusic();
}

void sdlMusic::stop(){
	Mix_HaltMusic();
}

bool sdlMusic::fadeOut(int ms){
	if (!this->isPlaying()){
		return false;
	}
	return Mix_FadeOutMusic(ms);
}

void sdlMusic::changeState(){
	if (this->isPaused()){
		this->resume();
	} else if (!this->isPaused() && this->isPlaying()){
		this->pause();
	}
}

sdlMusic::~sdlMusic(){
	counter--;
	Mix_FreeMusic(this->music);
	if (counter == 0){
		sdlMusicMonitor::eliminar();
		monitor = NULL;
	}
}
